package com.gzhryc.shared_device.oem.h5.mng.controllers.agent;

import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentMenu;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentLevel;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentLevelMenuRel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentMenuEnum;
import com.gzhryc.shared_device.oem.code.agent.services.AgentLevelMenuRelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentLevelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentMenuService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentMenuSearch;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.system.dto.MenuData;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AgentLevelMenuController {

    @Route("/agent/menu/list.html")
    public String list(HttpServletRequest request){
        return "/agent/menu/list.html";
    }

    @Route("/agent/menu/list.data")
    public ListResult<AgentMenu> listData(HttpServletRequest request){
        ListResult<AgentMenu> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");

        AgentMenuSearch search = WebUtils.getParameter(request,AgentMenuSearch.class);
        Integer pageNo = WebUtils.getInteger(request,"page",1);
        Integer pageLimit = WebUtils.getInteger(request,"limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(AgentMenuService.self().countBySearch(search));
        List<AgentMenu> menus = AgentMenuService.self().findBySearch(search, pageNo, pageLimit);
        if(menus != null && menus.size() > 0){
            result.setCode(DtoConstants.SUCCESS,null);
            result.getBody().setData(menus);
        }
        return result;
    }

    @Route("/agent/menu/add.html")
    public String add(HttpServletRequest request) {
        Long parentId = WebUtils.getLong(request,"parentId");
        if(parentId != null){
            AgentMenu agentMenu = AgentMenuService.self().getById(parentId);
            if(agentMenu != null){
                request.setAttribute("parentName",agentMenu.getName());
            }
        }
        request.setAttribute("typeList", AgentMenuEnum.Type.values());
        request.setAttribute("priority",10);
        return "/agent/menu/edit.html";
    }

    @Route(value="/agent/menu/add.do",method="post")
    public AjaxResult doAdd(HttpServletRequest request){
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败");
        AgentMenu menu = WebUtils.getParameter(request,AgentMenu.class);
        try {
            if(menu.getParentId() != null && menu.getParentId() == 0){
                menu.setParentId(null);
            }
            if(AgentMenuService.self().add(menu)){
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/agent/menu/update.html")
    public String update(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        if(id != null) {
            AgentMenu menu = AgentMenuService.self().getById(id);
            if(menu != null) {
                WebUtils.setAttribute(request, menu);
                if(menu.getParentId() != null){
                    AgentMenu parent = AgentMenuService.self().getById(menu.getParentId());
                    request.setAttribute("parentName",parent.getName());
                }
            }
        }
        request.setAttribute("typeList", AgentMenuEnum.Type.values());
        return "/agent/menu/edit.html";
    }

    @Route(value="/agent/menu/update.do",method="post")
    public AjaxResult doUpdate(HttpServletRequest request){
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败");
        AgentMenu menu = WebUtils.getParameter(request, AgentMenu.class);
        try {
            if(menu.getParentId() != null && menu.getParentId() == 0){
                menu.setParentId(null);
            }
            if(AgentMenuService.self().updateNotNull(menu)){
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value="/agent/menu/del.do")
    public AjaxResult delete(HttpServletRequest request){
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败");
        Long id = WebUtils.getLong(request,"id");
        if(id != null){
            try {
                if(AgentMenuService.self().deleteById(id)){
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
    
    @Route(value="/agent/menu/child.data")
    public AjaxResult findByChild(HttpServletRequest request){
        AjaxResult result = new AjaxResult(DtoConstants.NULL_DATA,"暂无数据");
        Long id = WebUtils.getLong(request,"id");
        if(id != null){
            List<AgentMenu> menuList = AgentMenuService.self().findByParentId(id);
            if(menuList != null && menuList.size() > 0){
                result.setCode(DtoConstants.SUCCESS, null);
                result.setBody(menuList);
            }
        }
        return result;
    }
    
    //配置代理级别的菜单

    @Route(value="/agent/level/menu/config.html",method="get")
    public String editMenu(HttpServletRequest request, HttpServletResponse response){
        Integer level = WebUtils.getInteger(request,"level");
        if(level != null){
            AgentLevel agentLevel = AgentLevelService.self().getByNum(level);
            if(agentLevel != null){
                request.setAttribute("agentLevel",agentLevel);
                List<AgentLevelMenuRel> list = AgentLevelMenuRelService.self().findJoinByLevel(level);
                List<MenuData> data = new ArrayList<MenuData>();
                if(list != null && list.size() > 0){
                    Map<Long,MenuData> map = new HashMap<Long,MenuData>();
                    for(AgentLevelMenuRel item : list){
                        MenuData temp = new MenuData();
                        temp.setId(item.getMenu().getId());
                        temp.setName(item.getMenu().getName());
                        temp.setChildren(new ArrayList<>());
                        map.put(temp.getId(), temp);  //临时保存
                        if(item.getMenu().getParentId() == null){
                            data.add(temp);
                        }else{
                            MenuData parent = map.get(item.getMenu().getParentId());
                            if(parent != null){
                                parent.getChildren().add(temp);
                            }
                        }
                    }
                }
                request.setAttribute("data", JsonTools.toJson(data));
                //获取所以根菜单
                request.setAttribute("rootMenuList", AgentMenuService.self().findRoot());
            }
        }
        return "/agent/menu/config.html";
    }

    @SuppressWarnings("unchecked")
    @Route(value="/agent/level/menu/config.do",method="post")
    public AjaxResult doEditMenu(HttpServletRequest request,HttpServletResponse response){
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"保存失败");
        Integer level = WebUtils.getInteger(request,"level");
        String data = request.getParameter("data");
        if(level != null && StringUtils.isNotBlank(data)){
            List<Map<String,Object>> list = JsonTools.fromJson(data, List.class);
            try {
                if(AgentLevelMenuRelService.self().save(level, list)){
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    
}
